package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Autowired
    private JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();

        //判断uri是否为白名单路径
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath,uri)){
                return chain.filter(exchange);
            }
        }
        //获取请求头中的令牌，如果获取不到，返回401
        String token = request.getHeaders().getFirst("Authorization");
        if (token==null || "".equals(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Long userId;
        //令牌token不对,返回401
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            log.error("令牌解析失败，请重新登录",e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //把令牌放请求头里传传到微服务
        request.mutate().header("user-info",userId.toString());

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
